<?php

abstract class Database_Exception extends CMS_Exception {

}

class Database_Driver_Exception extends Database_Exception {

	private $_driver;
	private $_child;

	public function getExceptionTrace(){
		return parent::getExceptionTrace() . (isset($this->_child) ? " " . $this->_child->getExceptionTrace() : "");
	}

	public function __toString(){
		return "({$this->_driver}) : ". parent::__toString() .(isset($this->_child) ? ' [' . $this->_child . ']' : '');
	}

	public function __construct($message, $driver, $child = null){
		$this->_driver = $driver;
		$this->_child = $child;
		parent::__construct($message);
	}

}

interface IDatabase {

	public function __construct($config);

}

interface IDatabase_Query {}
interface IDatabase_Select_Query extends IDatabase_Query {}
interface IDatabase_Insert_Query extends IDatabase_Query {}
interface IDatabase_Update_Query extends IDatabase_Query {}
interface IDatabase_Delete_Query extends IDatabase_Query {}

abstract class Database {

	private static $database;

	public static function getInstance(){
		if(!isset(Database::$database)){
			throw new Database_Exception("Database not loaded");
		}		
		return Database::$database;
	}

	public static function Load(){

		$config = Config::getInstance();

		try {

			CMS::File("database/{$config['database']['driver']}");
		
			$class = 'Database_' . $config['database']['driver'];

			if(!class_exists($class)){
				throw new Database_Driver_Exception('Database Driver Not Found', $config['database']['driver']);
			}
			if(!CMS::has_interface($class, 'IDatabase')){
				throw new Database_Driver_Exception('Database Driver Invalid', $config['database']['driver']);
			}

			Database::$database = new $class($config['database']);

		} catch (CMS_File_Exception $e){
			throw new Database_Driver_Exception('Database Driver File Not Found',$config['database']['driver'], $e);
		}


	}


}


